package com.lyfei.yd.security.service;

import com.lyfei.yd.admin.security.model.LoginUser;
import com.lyfei.yd.common.constant.CacheConstants;
import com.lyfei.yd.common.core.redis.RedisCache;
import com.lyfei.yd.common.enums.ErrorCode;
import com.lyfei.yd.common.exception.CustomException;
import com.lyfei.yd.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class SysLoginService {

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    /**
     * 登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @return 结果
     */
    public String login(String username, String password, String code, String uuid, boolean captchaEnabled) {

        if (captchaEnabled) {
            // 验证码校验
            validateCaptchaCode(username, code, uuid);
        }
        // 登录前置校验
        loginPreCheck(username, password);

        // 用户验证
        Authentication authentication = null;
        try {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager
                    .authenticate(new UsernamePasswordAuthenticationToken(username, password));
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                throw new CustomException(ErrorCode.USER_PASSWORD_NOT_MATCH.getMsg(), ErrorCode.USER_PASSWORD_NOT_MATCH.getCode());
            } else {
                throw new CustomException(e.getMessage());
            }
        }
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        // 生成token
        return tokenService.createToken(loginUser);
    }

    private void validateCaptchaCode(String username, String code, String uuid) {
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
        String captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);

        if (captcha == null) {
            throw new CustomException("验证码已失效");
        }
        if (!code.equalsIgnoreCase(captcha)) {
            throw new CustomException("验证码不正确");
        }
    }

    /**
     * 登录前置校验
     * @param username 用户名
     * @param password 用户密码
     */
    public void loginPreCheck(String username, String password) {
        if(StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            throw new CustomException("用户名或密码不正确");
        }

        if(password.length() < 6 || password.length() > 20) {
            throw new CustomException("密码长度不正确, 请输入6到20位的密码");
        }

        if(username.length() < 3 || username.length() > 20) {
            throw new CustomException("用户名长度不正确, 请输入3到20位的用户名");
        }
    }
}
